#include <iostream>
#include "Log.hpp"
#include "Reactor.hpp"
#include "Listener.hpp"
#include "Channel.hpp"
#include "Common.hpp"
#include "Protocol.hpp"
#include "NetCal.hpp"

using namespace LogModule;

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(USAGE_ERR);
    }
    // ConsoleLogstrategy();
    Enable_Console_Log_Strtegy();
    uint16_t port = std::stoi(argv[1]);
    // 构建业务模块
    std::shared_ptr<Cal> cal = std::make_shared<Cal>();

    // 构建协议模块
    std::shared_ptr<Protocol> protocol = std::make_shared<Protocol>([&cal](Request &req) -> Response{
        return cal->Execute(req);
    });

    // 构建listener对象，来控制所有的Connection和回调函数的设置
    std::shared_ptr<Connection> conn = std::make_shared<Listener>(port);
    
    conn->RegisterHandler([&protocol](std::string &inbuffer)->std::string{
        LOG(LogLevel::DEBUG) << "进入匿名函数";
        std::string response_str;
        while(true)
        {
            std::string package;
            if(!protocol->Decode(inbuffer,&package))
                break; //没有完整的报文，回调函数调用结束`

            //到这里一定是一个完整的请求
            response_str += protocol->Execute(package);
            //再去序列化，发送
            // channel->AppendOutBuffer(response_str);
        }

        LOG(LogLevel::DEBUG) << "结束匿名函数" << response_str;
        return response_str;
    });

    // 负责业务派发的reactor模块
    std::unique_ptr<Reactor> R = std::make_unique<Reactor>();
    R->AddConnection(conn);

    R->Loop();

    return 0;
}